<template>
  <div>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @selection-change="selectionChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template #menuLeft>
        <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAdd">新增</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" @click="handleDelete()">删除</el-button>
      </template>
      <template #menu="{ row }">
        <el-button type="text" size="small" @click="handleView(row)">详情</el-button>
        <el-button type="text" size="small" icon="el-icon-delete" @click="handleEdit(row)">编辑</el-button>
        <el-button type="text" size="small" icon="el-icon-delete" @click="handleDelete(row)">删除</el-button>
      </template>
    </avue-crud>
    <common-modal-template ref="commonModalTemplate" :key="timer" :option="tableOption" @getSelectedRows="getSelectedRows" @newKey="newKey"></common-modal-template>
    <el-dialog append-to-body :visible="tableDialog.visible" :title="tableDialog.title" close-on-press-escape destroy-on-close @close="onCancel" top="3vh" width="60%">
      <div class="sail-header-dialog-content">
        <avue-form v-model="form" :option="formOption" ref="form"></avue-form>
        <avue-crud
          ref="sonTable"
          :data="sonTableData"
          :option="sonTableOption"
          @row-update="rowUpdate"
          @row-save="rowSave"
          @row-del="rowDel"
          @selection-change="sonSelectionChange"
        >
          <template #menuLeft>
            <el-button type="danger" size="small" icon="el-icon-delete" @click="handleDeleteSon" v-if="tableDialog.title !== '详情'">删除</el-button>
          </template>
        </avue-crud>
      </div>
      <div slot="footer">
        <el-button size="small" @click="onCancel">取消</el-button>
        <el-button size="small" type="primary" @click="handleSubmitInfo" v-if="tableDialog.title !== '详情'">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { add, getList, remove, getDetail, getDetailTableData } from '@/api/admin/packid-validate-config';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';

export default {
  name: '', // 会渲染成传入的componentName
  components: { CommonModalTemplate },
  data() {
    return {
      timer: new Date().getTime(),
      form: {},
      query: {},
      selection: [],
      sonSelection: [],
      loading: false,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      data: [],
      tableDialog: {
        title: '新增',
        visible: false
      },
      tableOption: {},
      option: {
        calcHeight: 30,
        height: 'calc(100vh - 430px)',
        selection: true,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        addBtn: false,
        indexLabel: '序号',
        columnBtn: false,
        column: [
          {
            label: '规则编码',
            prop: 'code',
            search: true
          },
          {
            label: '规则名称',
            prop: 'name',
            search: true
          },
          {
            label: '规则类型',
            prop: 'type'
          },
          {
            label: '供应商',
            prop: 'vendorName',
            search: true
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      },
      formOption: {
        searchShow: true,
        searchMenuSpan: 6,
        menuPosition: 'right',
        submitBtn: false,
        emptyBtn: false,
        group: [
          {
            label: '基础信息',
            prop: 'equipmentInfo',
            arrow: false,
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            column: [
              {
                label: '规则编码',
                prop: 'code',
                span: 12,
                rules: [{ required: true, message: '请输入规则编码', trigger: 'blur' }]
              },
              {
                label: '规则名称',
                prop: 'name',
                span: 12,
                rules: [{ required: true, message: '请输入规则名称', trigger: 'blur' }]
              },
              {
                label: '规则类型',
                prop: 'type',
                span: 12,
                rules: [{ required: true, message: '请输入规则类型', trigger: 'blur' }]
              },
              {
                label: '正则表达式',
                prop: 'verifyingRegularity',
                span: 12,
                rules: [{ required: true, message: '请输入正则表达式', trigger: 'blur' }]
              },
              {
                label: '供应商',
                prop: 'vendorName',
                type: 'search',
                readOnly: true,
                appendClick: () => {
                  this.openVendorCommonModal();
                },
                span: 12
              },
              {
                label: '备注',
                prop: 'remark',
                span: 12
              }
            ]
          },
          {
            label: '字符详情',
            prop: 'equipmentInfo',
            arrow: false,
            icon: 'el-icon-vertical-bar',
            labelWidth: 100
          }
        ]
      },
      sonTableData: [],
      needDeletedExtractIds: [], //记录删除的数据的id
      sonTableOption: {
        calcHeight: 30,
        labelWidth: 120,
        dialogWidth: '40%',
        selection: true,
        tip: false,
        searchShow: false,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: true,
        editBtn: true,
        delBtn: true,
        addBtn: true,
        indexLabel: '序号',
        columnBtn: false,
        column: [
          {
            label: '字符编码',
            prop: 'code',
            rules: [{ required: true, message: '请输入字符编码', trigger: 'blur' }]
          },
          {
            label: '字符名称',
            prop: 'name',
            rules: [{ required: true, message: '请输入字符名称', trigger: 'blur' }]
          },
          {
            label: '正则表达式',
            prop: 'regex',
            rules: [{ required: true, message: '请输入正则表达式', trigger: 'blur' }]
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      }
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission, false),
        viewBtn: this.vaildData(this.permission, false),
        delBtn: this.vaildData(this.permission, false),
        editBtn: this.vaildData(this.permission, false)
      };
    },
    ids() {
      return this.selection.map((item) => item.id).join(',');
    }
  },
  methods: {
    rowSave(row, done, loading) {
      console.log(row);
      done(row);
    },
    rowUpdate(row, index, done, loading) {
      // this.sonTableData.splice(index, 1, row);
      done(row);
    },
    sonSelectionChange(list) {
      this.sonSelection = list;
    },
    handleDeleteSon() {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 将删除的数据的id记录下来在 needDeletedExtractIds 中
        this.sonSelection.forEach((item) => {
          if (item.id) {
            this.needDeletedExtractIds.push(item.id);
          }
        });
        this.sonTableData = this.sonTableData.filter((item) => !this.needDeletedExtractIds.includes(item.id));
        this.sonSelection = [];
      });
    },
    rowDel(row, index) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (row.id) {
          this.needDeletedExtractIds.push(row.id);
        }
        this.sonTableData.splice(index, 1);
      });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    selectionChange(list) {
      this.selection = list;
    },
    async onLoad(page, params = {}) {
      this.loading = true;
      try {
        const res = await getList(page.currentPage, page.pageSize, Object.assign(params, this.query));
        const data = res.data.data;
        this.data = data.records;
        this.page.total = data.total;
      } catch (e) {
        console.warn(e);
      } finally {
        this.loading = false;
      }
    },
    async handleView(row) {
      await this.getTableDetail(row);
      this.setFormViewStatus();
      this.tableDialog = { visible: true, title: '详情' };
    },
    setFormViewStatus() {
      this.$set(this.formOption, 'detail', true);
      this.$set(this.sonTableOption, 'menu', false);
      this.$set(this.sonTableOption, 'addBtn', false);
      this.$set(this.sonTableOption, 'selection', false);
    },
    setFormEditStatus() {
      this.$set(this.formOption, 'detail', false);
      this.$set(this.sonTableOption, 'menu', true);
      this.$set(this.sonTableOption, 'addBtn', true);
      this.$set(this.sonTableOption, 'selection', true);
      this.$refs.sonTable && this.$refs.sonTable.refreshTable();
    },
    handleAdd() {
      this.setFormEditStatus();
      this.tableDialog = { visible: true, title: '新增' };
    },
    async handleEdit(row) {
      await this.getTableDetail(row);
      this.setFormEditStatus();
      this.tableDialog = { visible: true, title: '编辑' };
    },
    async getTableDetail(row) {
      try {
        const res = await getDetail(row.id);
        const tableRes = await getDetailTableData(row.id);
        this.form = res.data.data;
        this.sonTableData = tableRes.data.data || [];
        this.needDeletedExtractIds = [];
      } catch (e) {
        console.warn(e);
      }
    },
    onCancel() {
      this.$refs.form.resetFields();
      this.sonTableData = [];
      this.tableDialog.visible = false;
    },
    handleSubmitInfo() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const data = {
            ...this.form,
            extractDTOS: this.sonTableData,
            needDeletedExtractIds: this.needDeletedExtractIds
          };
          try {
            const res = await add(data);
            this.onCancel();
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.onLoad(this.page);
          } catch (e) {}
        }
      });
    },
    handleDelete(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const ids = row ? row.id : this.ids;
          return remove(ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    getSelectedRows(rowData) {
      this.form.vendorCode = rowData.map((item) => item.code).join(',');
      this.form.vendorName = rowData.map((item) => item.name).join(',');
    },
    newKey() {
      this.timer = new Date().getTime();
    },
    /**
     * 打开供应商选择模态框
     */
    openVendorCommonModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择供应商信息（双击进行选择）',
        url: '/api/mes-admin/vendor/page',
        isPage: true,
        menu: false,
        editBtn: false,
        menuWidth: 100,
        columnDefs: [
          {
            label: '编码',
            prop: 'code',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          }
        ]
      };
    }
  }
};
</script>
<style lang="scss" scoped>
.no-print {
  display: none;
}
</style>
